import React, { useRef, useEffect } from 'react'

interface PieData {
  name: string
  value: number
  color: string
}

interface PieChartCardProps {
  title: string
  data: PieData[]
  monthOnMonth?: number
  yearOnYear?: number
}

const PieChartCard: React.FC<PieChartCardProps> = ({ title, data, monthOnMonth, yearOnYear }) => {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const animationProgress = useRef(0)

  useEffect(() => {
    const canvas = canvasRef.current
    if (!canvas) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    // 设置画布大小
    const size = 200
    canvas.width = size
    canvas.height = size

    // 计算总值
    const total = data.reduce((sum, item) => sum + item.value, 0)
    
    // 饼图配置
    const centerX = size / 2
    const centerY = size / 2
    const radius = 70
    const innerRadius = 35 // 内环半径，创建环形图效果

    // 动画函数
    const animate = () => {
      // 清除画布
      ctx.clearRect(0, 0, size, size)

      let currentAngle = -Math.PI / 2 // 从顶部开始
      let accumulatedProgress = 0

      // 绘制每个扇形（带动画）
      data.forEach((item) => {
        const sliceAngle = (item.value / total) * 2 * Math.PI
        const sliceProgress = (item.value / total)
        
        // 计算这个扇形的动画进度
        const startProgress = accumulatedProgress
        const endProgress = accumulatedProgress + sliceProgress
        accumulatedProgress = endProgress

        // 判断这个扇形是否应该开始绘制
        if (animationProgress.current >= startProgress) {
          // 计算当前扇形的绘制进度
          const sliceAnimationProgress = Math.min(
            1,
            (animationProgress.current - startProgress) / sliceProgress
          )

          // 绘制外环（带动画）
          ctx.beginPath()
          const animatedSliceAngle = sliceAngle * sliceAnimationProgress
          ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + animatedSliceAngle)
          ctx.arc(centerX, centerY, innerRadius, currentAngle + animatedSliceAngle, currentAngle, true)
          ctx.closePath()
          
          // 使用渐变色
          const gradient = ctx.createRadialGradient(
            centerX + Math.cos(currentAngle + animatedSliceAngle / 2) * 20,
            centerY + Math.sin(currentAngle + animatedSliceAngle / 2) * 20,
            innerRadius,
            centerX,
            centerY,
            radius
          )
          gradient.addColorStop(0, item.color)
          gradient.addColorStop(1, item.color + 'AA')
          ctx.fillStyle = gradient
          ctx.fill()

          // 添加边框
          ctx.strokeStyle = item.color
          ctx.lineWidth = 2
          ctx.stroke()

          // 更新角度（只更新已绘制的部分）
          currentAngle += animatedSliceAngle
        }
      })

      // 绘制中心圆（带动画）
      if (animationProgress.current > 0.3) {
        const centerProgress = Math.min(1, (animationProgress.current - 0.3) / 0.2)
        ctx.beginPath()
        ctx.arc(centerX, centerY, innerRadius * centerProgress, 0, 2 * Math.PI)
        ctx.fillStyle = '#f8fafc'
        ctx.fill()
        ctx.strokeStyle = '#e2e8f0'
        ctx.lineWidth = 1
        ctx.stroke()
      }

      // 更新动画进度
      if (animationProgress.current < 1) {
        animationProgress.current += 0.02
        requestAnimationFrame(animate)
      } else {
        animationProgress.current = 1
      }
    }

    // 重置动画进度并开始动画
    animationProgress.current = 0
    const animationId = requestAnimationFrame(animate)

    return () => {
      cancelAnimationFrame(animationId)
    }
  }, [data])

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 hover:shadow-lg transition-shadow duration-300 overflow-hidden">
      {/* 标题 */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h3 className="text-lg font-bold text-gray-800 mb-1">{title}</h3>
          <p className="text-xs text-gray-500">数据分布分析</p>
        </div>
        <button className="px-3 py-1.5 text-blue-600 text-sm font-medium hover:bg-blue-50 rounded-lg transition-all duration-200 hover:scale-105">
          更多
        </button>
      </div>

      {/* 饼图和图例 */}
      <div className="flex items-center justify-center">
        {/* 饼图 */}
        <div className="relative">
          <canvas ref={canvasRef} className="block drop-shadow-lg" />
          {/* 中心文字 */}
          <div className="absolute inset-0 flex flex-col items-center justify-center">
            <div className="text-xs text-gray-500 font-medium">总计</div>
            <div className="text-xl font-bold bg-gradient-to-r from-gray-800 to-gray-600 bg-clip-text text-transparent">
              {data.reduce((sum, item) => sum + item.value, 0)}%
            </div>
          </div>
        </div>
      </div>

      {/* 图例 */}
      <div className="mt-6 space-y-3">
        {data.map((item) => (
          <div key={item.name} className="flex items-center justify-between p-2 rounded-lg hover:bg-gray-50 transition-colors duration-200 group">
            <div className="flex items-center">
              <div 
                className="w-4 h-4 rounded-full mr-3 shadow-sm ring-2 ring-white group-hover:scale-110 transition-transform duration-200"
                style={{ backgroundColor: item.color }}
              />
              <span className="text-sm font-medium text-gray-700 group-hover:text-gray-900 transition-colors">{item.name}</span>
            </div>
            <div className="text-sm font-bold text-gray-900">
              {item.value}%
            </div>
          </div>
        ))}
      </div>

      {/* 底部统计 */}
      {(monthOnMonth !== undefined || yearOnYear !== undefined) && (
        <div className="mt-6 pt-4 border-t border-gray-100">
          <div className="grid grid-cols-2 gap-4">
            {monthOnMonth !== undefined && (
              <div className="text-center p-3 bg-green-50 rounded-xl border border-green-200">
                <div className="text-xs text-gray-600 mb-1">环比增长</div>
                <div className="text-base font-bold text-green-600">
                  {monthOnMonth > 0 ? '+' : ''}{monthOnMonth.toFixed(1)}%
                </div>
              </div>
            )}
            {yearOnYear !== undefined && (
              <div className="text-center p-3 bg-blue-50 rounded-xl border border-blue-200">
                <div className="text-xs text-gray-600 mb-1">同比增长</div>
                <div className="text-base font-bold text-blue-600">
                  {yearOnYear > 0 ? '+' : ''}{yearOnYear.toFixed(1)}%
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  )
}

export default PieChartCard


